<?php
use App\Model\TAUser;
use App\Model\TAUserWallet;
use App\Model\TAUserWalletsGoldBeanLog;
use App\Model\TGoldBeanTask;
use App\Model\TRouteEvent;
use App\Model\TSigninTask;
use App\Model\TSigninTaskUser;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class GoldBean
{
    /**
     * @Inject
     * @var TGoldBeanTask
     */
    public $tgoldBeanTask;

    /**
     * @Inject
     * @var TSigninTask
     */
    public $tSigninTask;

    /**
     * @Inject
     * @var TSigninTaskUser
     */
    public $tSigninTaskUser;


    /**
     * @Inject
     * @var TAUserWalletsGoldBeanLog
     */
    public $taUserWalletsGoldBeanLog;


    /**
     * @Inject
     * @var TRouteEvent
     */
    protected $routeEventModel;


    /**
     * @Inject
     * @var TAUserWallet
     */
    protected $tAUserWallet;


    /**
     * @Inject
     * @var TAUserWalletsMapper
     */
    protected $tAUserWalletMapper;


    /**
     * 获取金豆任务列表
     */
    public function goldTaskList($user_id)
    {
        $todayDatetime = timeChange(1);
        $where = [
            ["show", "=", 1],
            ["task_num",">",0]
        ];
        $getList = $this->tgoldBeanTask::query()
            ->select(["task_id", "icon", "name", "describe", "gold_bean", "task_num", "event_id"])
            ->where($where)
            ->orderBy("sort", 'asc')
            ->get()
            ->toArray();
        foreach ($getList as $key => $value) {

            $eventNo = '';
            $eventParams = '';
            if ($value['event_id'] > 0) {
                $eventInfo = $this->routeEventModel::find($value['event_id']);
                if ($eventInfo && $eventInfo->status == 1 && $eventInfo->deleted == 0) {
                    $eventNo = $eventInfo->event_no;
                    $eventParams = $eventInfo->event_params;
                }
            }
            $getList[$key]['eventNo'] = $eventNo;
            $getList[$key]['eventParams'] = $eventParams;

            $walletsGoldBean = $this->walletsGoldBeanLog($user_id, $value['task_id'], $todayDatetime);
            $getList[$key]['finishCount'] = $walletsGoldBean['count'];
            $getList[$key]['todayGain'] = (int)$walletsGoldBean['sum'];
        }
        return $getList;
    }


    /**
     * 查看今天的任务次数是否已经完成
     */
    public function walletsGoldBeanLog($user_id, $type, $datetime = [])
    {
        $where = [
            ['user_id', '=', $user_id],
            ['type', '=', $type],
            ['created', ">=", $datetime['start_at']],
            ['created', "<=", $datetime['end_at']]
        ];
        $goldBeanSum = $this->taUserWalletsGoldBeanLog::query()
            ->selectRaw("count(user_id) as count,sum(num) as sum")
            ->where($where)
            ->first();
        if ($goldBeanSum) {
            $responseResult = $goldBeanSum->toArray();
        } else {
            $responseResult = [
                'count' => 0,
                'sum' => 0
            ];
        }
        $responseResult['sum'] = (isset($responseResult['sum']) && !empty($responseResult['sum'])) ? (int)$responseResult['sum'] : 0;
        return $responseResult;
    }


    /**
     * 签到列表
     */
    public function signInList($user_id)
    {
        $signinUserTask = $this->tSigninTaskUser::query()
            ->where("user_id", "=", $user_id)
            ->orderBy("signin_time", "DESC")
            ->first();

        $getList = $this->tSigninTask::query()
            ->select(["signin_id", "name", "gold_bean", "extra_award"])
            ->get()
            ->toArray();
        $i = 0;
        foreach ($getList as $key => $value) {
            $getList[$key]["name"] = "第{$value['signin_id']}天";//$signinUserTask->day == $value['signin_id'] ? "今天" : "第{$value['signin_id']}天";
            $getList[$key]["isSign"] = 0;
            if (isset($signinUserTask->day)) {
                $getList[$key]["isSign"] = $signinUserTask->day >= $value['signin_id'] ? 1 : 0;
                if ($signinUserTask->day >= $value['signin_id']) {
                    $i++;
                }
            }
        }
        $TUserWallet = $this->tAUserWallet::query()->where("user_id","=",$user_id)->first();
        $responseResult['list'] = $getList;
        $responseResult['signinDayCount'] = $i;     //连续签到天数
        $responseResult['goldBean'] = $TUserWallet->gold_bean;      //我的金豆余额
        return $responseResult;
    }


    /**
     * 用户签到
     */
    public function signIn($user_id)
    {
        $response = $this->addSigninTaskUser($user_id);
        return $response;
    }


    /**
     * 签到添加记录
     */
    private function addSigninTaskUser($user_id)
    {
        $todayDate = date("Y-m-d");
        $tSigninTaskUser = $this->tSigninTaskUser::query()
            ->where("user_id", "=", $user_id)
            ->orderBy("signin_time", "DESC")
            ->first();
        if (!$tSigninTaskUser) {      //没有数据 代表用户第一天签到
            Db::beginTransaction();
            $tSigninTask = $this->tSigninTask::query()->where("signin_id", "=", 1)->first()->toArray();
            $TSigninTaskUserDb = new TSigninTaskUser();
            $TSigninTaskUserDb->user_id = $user_id;
            $TSigninTaskUserDb->gold_bean = $tSigninTask['gold_bean'];
            $TSigninTaskUserDb->extra_award = $tSigninTask['extra_award'];
            $TSigninTaskUserDb->signin_time = $todayDate;
            $TSigninTaskUserDb->created = date("Y-m-d H:i:s");
            $TSigninTaskUserDb->updated = date("Y-m-d H:i:s");
            $TSigninTaskUserDb->day = 1;
            if (!$TSigninTaskUserDb->save()) {
                Db::rollBack();
                return ['status' => false, 'msg' => '签到发放奖励错误'];
            }
            if ($tSigninTask['gold_bean']) {
                $responseGoldBean = $this->tAUserWalletMapper->setGoldBean($user_id, 7, 1, (int)$tSigninTask['gold_bean'], "第1天签到奖励");
                if (!$responseGoldBean['status']) {
                    Db::rollBack();
                    return ['status' => false, 'msg' => '签到发放奖励错误'];
                }
            }
            if ($tSigninTask['extra_award']) {
                $responseGoldBeanTwo = $this->tAUserWalletMapper->setGoldBean($user_id, 7, 1, (int)$tSigninTask['extra_award'], "第1天签到额外奖励");
                if (!$responseGoldBeanTwo['status']) {
                    Db::rollBack();
                    return ['status' => false, 'msg' => '签到发放奖励错误'];
                }
            }
            $data = ['status' => 1, 'gold_bean' => $tSigninTask['gold_bean'], 'extra_award' => $tSigninTask['extra_award']];
            Db::commit();
        } else {
            $data = ['status' => 2, 'gold_bean' => $tSigninTaskUser->gold_bean, 'extra_award' => $tSigninTaskUser->extra_award];
            if ($tSigninTaskUser->signin_time != $todayDate) {    //数据库最后一次签到的日期不是今天，代表今天没有签到
                Db::beginTransaction();
                $tSigninTask = $this->tSigninTask::query()->where("signin_id", "=", 1)->first()->toArray();
                $TSigninTaskUserDb = new TSigninTaskUser();
                $TSigninTaskUserDb->gold_bean = $tSigninTask['gold_bean'];
                $TSigninTaskUserDb->extra_award = $tSigninTask['extra_award'];
                $TSigninTaskUserDb->signin_time = $todayDate;
                $TSigninTaskUserDb->user_id = $user_id;
                $TSigninTaskUserDb->created = date("Y-m-d H:i:s");
                $TSigninTaskUserDb->updated = date("Y-m-d H:i:s");
                $TSigninTaskUserDb->day = 1;
                $yestodayData = date('Y') . "-" . date('m') . '-' . (date('d') - 1);
                if ($tSigninTaskUser->signin_time == $yestodayData) { //数据库最后一次签到的日期等于昨天，代表用户连续签到
                    $day = $tSigninTaskUser->day >= 7 ? 1 : $tSigninTaskUser->day + 1;
                    $tSigninTask = $this->tSigninTask::query()->where("signin_id", "=", $day)->first()->toArray();
                    $TSigninTaskUserDb->day = $day;
                    $TSigninTaskUserDb->gold_bean = $tSigninTask['gold_bean'];
                    $TSigninTaskUserDb->extra_award = $tSigninTask['extra_award'];
                }
                if (!$TSigninTaskUserDb->save()) {
                    Db::rollBack();
                    return ['status' => false, 'msg' => '签到发放奖励错误'];
                }
                if ($tSigninTask['gold_bean']) {
                    $responseGoldBean = $this->tAUserWalletMapper->setGoldBean($user_id, 7, 1, (int)$tSigninTask['gold_bean'], "第{$TSigninTaskUserDb->day}天签到奖励");
                    if (!$responseGoldBean['status']) {
                        Db::rollBack();
                        return ['status' => false, 'msg' => '签到发放奖励错误'];
                    }
                }
                if ($tSigninTask['extra_award']) {
                    $responseGoldBeanTwo = $this->tAUserWalletMapper->setGoldBean($user_id, 7, 1, (int)$tSigninTask['extra_award'], "第{$TSigninTaskUserDb->day}天签到额外奖励");
                    if (!$responseGoldBeanTwo['status']) {
                        Db::rollBack();
                        return ['status' => false, 'msg' => '签到发放奖励错误'];
                    }
                }
                $data = ['status' => 1, 'gold_bean' => $tSigninTask['gold_bean'], 'extra_award' => $tSigninTask['extra_award']];
                Db::commit();
            }
        }
        return ['status' => true, 'msg' => '获取成功', 'data' => $data];
    }


    /**
     * 金豆去完成任务
     */
    public function taskType($user_id, $taskId)
    {
        $extends = "";
        $goldBeanTask = $this->tgoldBeanTask::query()
            ->where("task_id", "=", $taskId)
            ->first();
        $today = timeChange(1);
        $goldBeanLog = $this->walletsGoldBeanLog($user_id, $goldBeanTask->task_id, $today);

        switch ($taskId){
            case 1: //邀请好友下单奖励
                $where = [
                    ['user_id','=',$user_id],
                    ['created',">=","2022-06-21 00:00:00"]
                ];
                $tAUserDb = new TAUser();
                $tAUser = $tAUserDb::query()->where($where)->first();
                if($tAUser){
                    //判断上级用户是否已经加了金豆 ，每人只能加一次
                    $isAwardInviterUser = $this->taUserWalletsGoldBeanLog::query()
                        ->where([["type","=",1],["extends","=",$user_id]])
                        ->first();
                    if($isAwardInviterUser){
                        return ['status'=>false,'msg'=>'当前邀请用户已经奖励过金豆'];
                    }
                    //判断上级邀请人加金豆
                    if($tAUser->inviter_user_id){
                        $extends = $user_id;            //记录当前邀请的用户id
                        $user_id = $tAUser->inviter_user_id;
                        $inviterGoldBeanLog = $this->walletsGoldBeanLog($user_id, $goldBeanTask->task_id, $today);      //判断当前用户今天获得金豆数量
                        $tcDictionary = new TCDictionaryMapper();
                        $tcDictionaryUser = $tcDictionary->getFirstByDicCode("gold_bean_limit");
                        if($inviterGoldBeanLog['sum'] > $tcDictionaryUser['dic_value']){
                            return ['status'=>false,'msg'=>"邀请好友下单，每天上限最多可获取{$tcDictionaryUser['dic_value']}个金豆"];
                        }
                    }else{
                        return ['status'=>false,'msg'=>'没有找到上级邀请人'];
                    }
                }else{
                    return ['status'=>false,'msg'=>'当前用户是老用户'];
                }
                break;
        }




        if ($goldBeanLog['count'] < $goldBeanTask->task_num) {      //每天完成的任务次数
            if ($goldBeanTask->gold_bean > 0) {
                $this->tAUserWalletMapper->setGoldBean((int)$user_id, (int)$goldBeanTask->task_id, 1, (int)$goldBeanTask->gold_bean, (string)$goldBeanTask->log_title,(string)$extends);
            }
        }
        return ['status' => true, 'msg' => '成功', 'data' => []];
    }


    /**
     * 金豆详情
     */
    public function goldBeanLog($user_id, $page, $pageSize)
    {
        if ($page > 0) {
            $page = ($page - 1) * $pageSize;
        }
        $result = $this->taUserWalletsGoldBeanLog::query()
            ->where("user_id", "=", $user_id)
            ->offset($page)
            ->orderBy("updated","DESC")
            ->limit($pageSize)
            ->get()
            ->toArray();
        return $result;
    }

    //-------------------------------------------------------------------------------------------------------------------后台----------------------------------------------------
    public function adminSignList(){
        $responseResult = $this->tSigninTask::query()
            ->get()
            ->toArray();
        return $responseResult;
    }



    /**
     * 修改签到任务
     */
    public function updateSign($params){
        $TSigninTaskDb = new TSigninTask();
        foreach($params as $key=>$value){
            $TSigninTask = $TSigninTaskDb::query()->where("signin_id","=",$value['signinId'])->first();
            $TSigninTask->gold_bean = $value['goldBean'];
            $TSigninTask->extra_award = $value['extraAward'];
            $TSigninTask->updated = date("Y-m-d H:i:s");
            if(!$TSigninTask->save()){
                return ['status'=>false,'msg'=>'修改失败'];
            }
        }
        return ['status'=>true,'msg'=>'修改成功'];
    }




    /**
     * 金豆任务列表
     */
    public function goldBeanTaskList(){
        $responseResult = $this->tgoldBeanTask::query()
            ->get()
            ->toArray();
        return $responseResult;
    }


    /**
     * 修改任务
     */
    public function goldBeanTaskUpdate($params){
        $TGoldBeanTaskDb = new TGoldBeanTask();
        foreach($params as $key=>$value){
            $TGoldBeanTask = $TGoldBeanTaskDb::query()->where("task_id","=",$value['taskId'])->first();
            $TGoldBeanTask->icon = $value['icon'];
            $TGoldBeanTask->name = $value['name'];
            $TGoldBeanTask->describe = $value['describe'];
            $TGoldBeanTask->gold_bean = $value['goldBean'];
            $TGoldBeanTask->task_num = $value['taskNum'];
            $TGoldBeanTask->event_id = $value['eventId'];
            $TGoldBeanTask->updated = date("Y-m-d H:i:s");
            if(!$TGoldBeanTask->save()){
                return ['status'=>false,'msg'=>'修改失败'];
            }
        }
        return ['status'=>true,'msg'=>'修改成功'];
    }

}